package byggeTegner;

import context.*;

import model2D.Model2D;
import model2D.ObjectTableModel;
import object2D.Object2D;

import java.awt.event.InputEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.JTable;
import javax.swing.ListSelectionModel;

// ********************************************************************
// *** CLASS: TableView
// ********************************************************************
public class TableView  extends JTable implements Context.Constants
{ //private static final boolean DEBUG=true; // Overriding Context.Constants.DEBUG
  static final String TAG="mainFrame.TableView";
  static final long serialVersionUID=0; // AD'HOC

  private ObjectTableModel objectTableModel;

  // ******************************************************************
  // *** CONSTRUCTOR: TableView
  // ******************************************************************
  public TableView(Model2D objectModel)
  { super();
    this.objectTableModel=objectModel.toObjectTableModel();
    this.setModel(objectTableModel);
    this.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    this.addMouseListener(new TableMouseAdapter());
    this.setRowHeight(20);
  }

  // ******************************************************************
  // *** METHOD: setSelected
  // ******************************************************************
  public void setSelected(Object2D selected)
  { int idx=objectTableModel.indexOf(selected);
	if(idx>=0) this.addRowSelectionInterval(idx,idx);	
  }

  // ******************************************************************
  // *** INNER CLASS: TableMouseAdapter
  // ******************************************************************
  private class TableMouseAdapter extends MouseAdapter
  { public void mousePressed(MouseEvent e)
	{ int flg=e.getModifiers();
	  if((flg& InputEvent.BUTTON1_MASK)!=0)
	       mouseLeftPressed(e.getX(),e.getY());
	  else mouseRightPressed(e.getX(),e.getY());
	}
    private void mouseLeftPressed(int x, int y)
    { if(DEBUG) Log.d(TAG,"MOUSE LEFT PRESSED: x="+x+", y="+y);
      int row=getSelectedRow();
      if(DEBUG) Log.d(TAG,"MOUSE RIGHT PRESSED: SelectedRow="+row);
      if(row>=0) objectTableModel.select(row);
    }  
    private void mouseRightPressed(int x, int y)
    { if(DEBUG) Log.d(TAG,"MOUSE RIGHT PRESSED: x="+x+", y="+y);
      int row=getSelectedRow();
      if(DEBUG) Log.d(TAG,"MOUSE RIGHT PRESSED: SelectedRow="+row);
      if(row>=0) objectTableModel.edit(row);
    }  
  }

}